import {
	objDeepCopy,
	getCascaderObj,
	getDateString
} from "@/assets/js/common.js";
let Controller = {
	created() {
		this.init();
	},
	mounted() {

	},
	methods: {
		init() {
			this.getAllProvince(this);
			this.getSalesClassification(this);
			this.getSalesGoodsGroup(this);
			this.getSelfLiftCity(this);
			
			this.getSourceChannel(this);//来源渠道
			this.getSupplierShop(this);//发货门店
		},
		//
		// 获取自提城市
		getSelfLiftCity(that) {
			var apiTest = this.apiTest;
			this.$ajax({
				method: 'get',
				url: apiTest + '/crm/geographyCity/queryCityList?language=1&countryCode=CN',
			}).then((res) => {
				var data = res.data;
				if (data.status == 200) {
					var result = data.result;
					that.Model.allCities = objDeepCopy(result);
				} else {
					that.tips(that, 'warning', data.msg)
				}

			});
		},
		//获取 门店
		getSupplierShop(that, city) {
			var apiTest = this.apiTest;
			this.$ajax({
				method: 'post',
				url: apiTest + '/supplier/supplierShop/getList',
				data: {
					city: city
				}
			}).then((res) => {
				var data = res.data;
				if (data.status == 200) {
					that.Model.cityStore = [];
					that.Model.deliverStores = [];  //发货门店
					var result = data.result;
					if (result) {
						that.Model.cityStore = objDeepCopy(result);
						that.Model.deliverStores = objDeepCopy(result);
					}

				} else {
					that.tips(that, 'warning', data.msg)
				}

			});
		},
		//展示发货门店
		deliveryWay(value) {
			if(value==1){
				this.Model.allStoresDisabled = false;
				// this.getSupplierShop(this);
			}	
		},
		//切换城市 获取门店信息
		queryStore(value) {
			this.getSupplierShop(this, value);
		},
		// 获取销售分类 下拉框(单个商品)
		getSalesClassification(that) {
			var apiTest = this.apiTest;
			this.$ajax({
				method: 'post',
				url: apiTest + '/sale/saleGoodsAttribute/getGoodsAttributelist',
				// url:'/api/sale/saleGoodsAttribute/getGoodsAttributelist',
				data: {
					attributeCode: "c06"
				}
			}).then((res) => {
				var data = res.data;
				if (data.status == 200) {
					that.Model.filterOption1.items[2].data = [];
					var result = data.result;
					var obj = {};
					for (var i = 0; i < result.length; i++) {
						obj = {
							label: result[i].propertyValueName,
							value: result[i].attributeValueCode
						}
						that.Model.filterOption1.items[2].data.push(obj);
					}
				} else {
					that.tips(that, 'warning', data.msg)
				}

			});
		},
		//获取 来源渠道 下拉框
		getSourceChannel(that){
			var apiTest = this.apiTest;
			this.$ajax({
				method: 'post',
				url: apiTest + '/sale/saleGoodsAttribute/getGoodsAttributelist',
				// url:'/api/sale/saleGoodsAttribute/getGoodsAttributelist',
				data: {
					attributeCode: "M23"
				}
			}).then((res) => {
				var data = res.data;
				if (data.status == 200) {
					that.Model.originChannelData.data = [];
					var result = data.result;
					var obj = {};
					for (var i = 0; i < result.length; i++) {
						obj = {
							label: result[i].attributeValueName,
							value: result[i].attributeValueCode
						}
						that.Model.originChannelData.push(obj)
					}
				} else {
					that.tips(that, 'warning', data.msg)
				}
			
			});
		},
		// 分组名称 下拉框（预选商品）
		getSalesGoodsGroup(that) {
			var apiTest = this.apiTest;
			this.$ajax({
				method: 'post',
				url: apiTest + '/sale/saleGoodsGroup/list',
				// url:'/api/sale/saleGoodsGroup/list',
				data: {}
			}).then((res) => {
				var data = res.data;
				if (data.status == 200) {
					that.Model.filterOption2.items[0].data = [];
					var result = data.result;
					var obj = {};
					for (var i = 0; i < result.length; i++) {
						obj = {
							label: result[i].name,
							value: result[i].id
						}
						that.Model.filterOption2.items[0].data.push(obj);
					}
				} else {
					that.tips(that, 'warning', data.msg)
				}

			});
		},
		//获取 单个现货商品(更换接口 2019.03.05)
		getCommodity(that, params) {
			var apiTest = this.apiTest;
			params = params || {}
			this.$ajax({
				method: 'post',
				url: apiTest + '/sale/saleOrder/getGoodsByCode',
				data: {
					condition: {
						commodityType: "Z001", //固定不变
						batchNo: params.batchNo,
					}
				}
			}).then((res) => {
				var data = res.data;
				if (data.status == 200) {
					that.Model.tableDataDialog = [];
					var result = data.result.result;
					console.log(result)
					var obj = {};
					for (var i = 0; i < result.length; i++) {
						obj = objDeepCopy(result[i]);
						//描述换行处理
						var str = result[i].description
						str=str.replace(/<br\/?>/gi,"\r\n");	
						obj.descriptionWord = str;
				
						that.Model.tableDataDialog.push(obj);
					}
				} else {
					that.tips(that, 'warning', data.msg)
				}

			});
		},
		//获取 预选商品
		getPreSelection(that, params) {
			var apiTest = this.apiTest;
			params = params || {}
			this.$ajax({
				method: 'post',
				url: apiTest + '/sale/saleGoodsGroupDetail/list',
				// url:'/api/sale/saleGoodsGroupDetail/list',
				data: params
			}).then((res) => {
				var data = res.data;
				if (data.status == 200) {
					that.Model.tableDataDialogGroup = [];
					var result = data.result.result;
					var obj = {};
					for (var i = 0; i < result.length; i++) {
						obj = objDeepCopy(result[i]);
						that.Model.tableDataDialogGroup.push(obj);
					}
				} else {
					that.tips(that, 'warning', data.msg)
				}

			});
		},
		//新增(现货/定制/补购)订单接口
		getNewOrder(that, params, pathName) {
			var apiTest = this.apiTest;
			// 			var params = this.Model.params;
			this.$ajax({
				method: 'post',
				url: apiTest + '/sale/saleOrder',
				// url:'/api/sale/saleOrder',
				data: params
			}).then((res) => {
				var data = res.data;
				this.Model.payPos = false;
				if (data.status == 200) {
					that.tips(that, 'success', '新增成功');
					var result = data.result;
					that.Model.linktoResult = result;

					if (pathName != 0) {
						var linktoResult = result;
						that.Model.payPos = false;
						that.$router.push({
							path: 'spotOrderDetail',
							query: {
								saleNumber: linktoResult.orderNo,
								id: linktoResult.id,
								to: pathName
							}
						});
					} else {
						//返回列表
						setTimeout(function() {
							that.$router.push({
								path: 'spotOrder',
								query: {
									isRefresh: true
								}
							});

						}, 1000)
					}
				} else {
					that.tips(that, 'warning', data.msg)
				}
			});
		},
		//点击 确认 查询男士身份证
		findman() {
			var IDCard = this.Model.params.idCard;
			if (IDCard) {
				this.isFirstBuy(this, IDCard);
				this.getUserMsg(this, IDCard, 'IDCard');
			} else {
				this.tips(this, 'warning', '请填写身份证号')
				return
			}

		},
		//失去焦点 电话号码查询 
		queryPhone() {
			var phoneNo = this.Model.params.mobile;
			var that = this;
			this.getUserMsg(this, phoneNo, 'phoneNo');
		},
		//通过身份证获取用户信息和收货地址
		getUserMsg(that, number, type) {
			if (number == '') {
				return;
			}
			var apiTest = this.apiTest;
			var url;
			if (type == 'IDCard') {
				url = apiTest + '/crm/customerInfo/sale/findByIDCard?IDCard=' + number;
				// url = '/api/crm/customerInfo/sale/findByIDCard?IDCard='+number;
			} else if (type == 'phoneNo') {
				url = apiTest + '/crm/customerInfo/sale/findByPhone?phoneNum=' + number;
				// url = '/api/crm/customerInfo/sale/findByPhone?phoneNum='+number;
			}
			this.$ajax({
				method: 'get',
				url: url,
			}).then((res) => {
				var data = res.data;
				if (data.status == 200) {
					var arr = [];
					var result = data.result;
					if (result) {
						that.Model.params.isNewUser = false;
						that.Model.basicMsgDisabled = true;
						that.Model.params.womanName = result.femaleName; //女士姓名
						that.Model.params.ladiesPhone = result.femalePhone; //女士手机号
						that.Model.params.manName = result.maleName; //男士姓名
						that.Model.params.mobile = result.phone; //男士手机号
						that.Model.params.sexuality = String(result.sexOrientation); //恋爱属性
						that.Model.params.exclusiveCode = result.exclusiveCode; //专属编码（第一次购买的 专属编码是 求婚女戒的定制编码）

						//
						var list = result.receiverInfoList;
						for (var i = 0; i < list.length; i++) {
							var locationName = list[i].geographyProvince.provinceName + list[i].geographyCity.cityName + list[i].geographyArea
								.areaName; //省市县组合的字段
							var obj = {
								id: list[i].id,
								recipientName: list[i].name,
								recipientPhone: list[i].phone,
								informPhone: list[i].informPhone,
								addressType: String(list[i].addressType),
								locationArea: [list[i].provinceCode, list[i].cityCode, list[i].areaCode],
								locationName: locationName,
								detailedAddress: list[i].address,
								alternativeAddress: '',
								defaultAddress: list[i].defaultAddress,
							}
							arr.push(obj);
							//是否默认
							if (list[i].defaultAddress == 1) {
								that.Model.radioAddress = list[i].id;
								//将默认地址填入 下方地址信息
								this.getAllCity(this, list[i].provinceCode);
								this.getAllCounty(this, list[i].provinceCode, list[i].cityCode)
								that.Model.selectedOptions3 = [list[i].provinceCode, list[i].cityCode, list[i].areaCode];
								//需要新增的地址信息
								that.Model.checkedAddress = {
									recipientName: list[i].name,
									recipientPhone: list[i].phone,
									informPhone: list[i].informPhone,
									addressType: String(list[i].addressType),
									locationArea: [list[i].provinceCode, list[i].cityCode, list[i].areaCode],
									locationName: locationName,
									detailedAddress: list[i].address,
									alternativeAddress: ''
								}
							}
						}
						that.Model.params.saleReceivingList = objDeepCopy(arr); //收货信息
					} else {
						that.Model.params.isNewUser = true;
						that.Model.params.womanName = '';
						that.Model.params.ladiesPhone = '';
						that.Model.params.manName = '';
						that.Model.params.sexuality = '';
						that.Model.basicMsgDisabled = false;
						that.Model.params.exclusiveCode = '';
					}
				} else {

				}

			});
		},

		//是否首次购买 接口
		isFirstBuy(that, IDCard) {
			var apiTest = this.apiTest;
			IDCard = IDCard || '';
			this.$ajax({
				method: 'get',
				url: apiTest + '/sale/saleOrder/buy/' + IDCard,
			}).then((res) => {
				var data = res.data;
				if (data.status == 200) {
					var result = data.result;
					// result:true 是第一次购买
					that.Model.womanRingStatus = true;
					that.Model.womanRingPay = !result;
				} else {
					that.tips(that, 'warning', data.msg)
				}

			});
		},
		//获取省
		getAllProvince(that) {
			var apiTest = this.apiTest;
			this.$ajax({
				method: 'get',
				url: apiTest + '/crm/geographyProvince/queryProvinceList?language=1&countryCode=CN',
				// url:'/api/crm/geographyProvince/queryProvinceList?language=1&countryCode=CN',
			}).then((res) => {
				var data = res.data;
				if (data.status == 200) {
					that.options = [];
					var result = data.result;
					for (var i = 0; i < result.length; i++) {
						var obj = {
							code: result[i].provinceCode,
							label: result[i].provinceName,
							children: []
						}
						that.Model.options.push(obj);
					}
				} else {

				}

			});
		},
		//获取市
		getAllCity(that, provinceCode) {
			var apiTest = this.apiTest;
			this.$ajax({
				method: 'get',
				url: apiTest + '/crm/geographyCity/queryCityList?language=1&countryCode=CN&provinceCode=' + provinceCode,
				// url:'/api/crm/geographyCity/queryCityList?language=1&countryCode=CN&provinceCode='+provinceCode,
			}).then((res) => {
				var data = res.data;
				if (data.status == 200) {
					var result = data.result;
					var options = that.Model.options;
					var cities = [];
					//遍历数据
					for (var i = 0; i < result.length; i++) {
						var obj = {
							code: result[i].cityCode,
							label: result[i].cityName,
							children: []
						}
						cities.push(obj);
					}
					//查找 相对应的省
					for (var i = 0; i < options.length; i++) {
						if (options[i].code == provinceCode) {
							options[i].children = objDeepCopy(cities);
						}
					}
				} else {

				}

			});
		},
		//获取区（县）
		getAllCounty(that, provinceCode, cityCode) {
			var apiTest = this.apiTest;
			this.$ajax({
				method: 'get',
				url: apiTest + '/crm/geographyArea/queryAreaList?language=1&countryCode=CN&provinceCode=' + provinceCode +
					'&cityCode=' + cityCode,
				// url:'/api/crm/geographyArea/queryAreaList?language=1&countryCode=CN&provinceCode='+provinceCode+'&cityCode='+cityCode,
			}).then((res) => {
				var data = res.data;
				if (data.status == 200) {
					var result = data.result;
					var areas = [];
					var options = that.Model.options;
					//遍历数据
					for (var i = 0; i < result.length; i++) {
						var obj = {
							code: result[i].areaCode,
							label: result[i].areaName
						}
						areas.push(obj);
					}
					//查找 相对应的区（县）
					for (var i = 0; i < options.length; i++) {
						if (options[i].code == provinceCode) {
							var cities = options[i].children;
							for (var j = 0; j < cities.length; j++) {
								if (cities[j].code == cityCode) {
									cities[j].children = objDeepCopy(areas);
								}
							}
						}
					}
				} else {

				}

			});
		},
		//点击加急
		handleClickApproval(row) {
			row.isExpedited = true;
		},
		//点击删除
		handleClickDelete(row) {
			var mainTableData = this.Model.mainTableData;
			var submitTableData = this.Model.submitTableData;
			var idData = this.Model.idData;
			var idx = mainTableData.indexOf(row);
			this.$confirm('此操作将永久删除该, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
			}).then(() => {
				mainTableData.splice(idx, 1);
				submitTableData.splice(idx, 1);
				idData.splice(idx, 1);
				this.$message({
					type: 'success',
					message: '删除成功!'
				});
			}).catch(() => {

			});
		},
		//点击添加商品
		addGoods(type) {
			if (type == 'single') {
				this.Model.dialogTableChecked = '';
				this.getCommodity(this);
				this.Model.changeGoodsDialogFlag = true;
			} else {
				this.getPreSelection(this);
				this.Model.changeGoodsDialogGroup = true;
			}
		},
		//点击确认添加商品
		addCommodity() {
			var commodityObject = this.Model.dialogTableChecked;
			var idCard = this.Model.params.idCard;
			if(idCard.length == 0){
				this.tips(this, 'warning', '请先填写身份证号再添加商品');
				return;
			}
			if (commodityObject.length == 0) {
				this.tips(this, 'warning', '请选择数据');
			} else {
				this.getPrice(this, commodityObject,idCard);
			}
		},
		//获取 商品的价格（2019.03.05修改，去掉原有的假价格,同时只能选择一个商品）
		getPrice(that, commodityObject,idCard) {
			var idData = this.Model.idData;
			var mainTableData = this.Model.mainTableData;
			var apiTest = this.apiTest;
			this.$ajax({
				method: 'get',
				url: apiTest + '/sale/saleOrder/getNowGoods/' + commodityObject.id+'/'+idCard,
			}).then((res) => {
				var data = res.data;
				if (data.status == 200) {
					var result = data.result;
					if (result) {
						var customGoodsVo = result.customGoodsVo;

						if (idData.indexOf(commodityObject.id) == -1) {
							
							for (let i = 0; i < mainTableData.length; i++) {
								if(customGoodsVo.salesType == 'M05001' && mainTableData[i].salesType == 'M05001'){
									this.tips(this, 'warning', '只能选择一个求婚钻戒');
									return;
								}else{
									
								}
							}
							//描述换行处理
							var str = result.describe
							str = str.replace(/<br\/?>/gi,"\r\n");	
							//
							that.Model.params.exclusiveCode = result.customNumber;//专属编码
							that.Model.idData.push(commodityObject.id);
							customGoodsVo.barCode = result.barCode; //条码
							customGoodsVo.goodsNo = result.goodsNo; //商品编码
							customGoodsVo.descriptionWord = str; //描述
							customGoodsVo.fee = result.fee; //定制服务费
							customGoodsVo.totalPrice = result.totalPrice; //应付总金额
							customGoodsVo.price = result.price; //商品金额
							customGoodsVo.warehouseName = result.warehouseName; //仓库地点
							customGoodsVo.amount = 1; //数量
							that.Model.mainTableData.push(customGoodsVo); //显示的数组数据

							var obj = result;
							obj.count = 1;
							that.Model.submitTableData.push(obj); //之后需要提交的数组（数据层次不一样）

						} else {
							that.tips(that, 'warning', '该商品已添加');
						}
					}
					

					that.Model.changeGoodsDialogFlag = false;
					that.Model.changeGoodsDialogGroup = false;

				} else {
					that.tips(that, 'warning', data.msg);
				}

			});
		},
		//点击 选择已有地址（点击切换地址）
		onChooseAddress() {
			var AddressId = this.Model.radioAddress;
			var AddressArr = this.Model.params.saleReceivingList;
			var AddressObj = this.getDataObj(AddressId, AddressArr);
			this.Model.checkedAddress = AddressObj;
			this.Model.selectedOptions3 = objDeepCopy(AddressObj.locationArea); //区域地址 联级选择器
			this.Model.changeAddress = false;
		},
		//遍历 得到label及value
		getDataObj(val, data) {
			var obj;
			data.forEach(function(value, index, array) {
				Object.keys(value).forEach(function(key) {
					// console.log(key,value[key]);
					if (key == 'id' && value[key] == val) {
						obj = value;
						return;
					}
				});
			})
			return obj;

		},
		//点击 提交订单
		onConfirmNew() {
			//判断非空
			
			let params = this.Model.params;
			if(params.idCard.length == 0){
				this.tips(this, 'error', '请填写身份证号');
				return;
			}
			if(this.Model.submitTableData.length == 0){
				this.tips(this, 'error', '请添加商品');
				return;
			}
			
			this.Model.payPos = true;
			var payMethod = this.Model.params.isPosPay; //支付方式
		},
		//确定提交
		onConfirmSubmit(pathName) {
			var params = this.Model.params;
			var submitTableData = this.Model.submitTableData;
			var arr = [];

			params.goodsList = submitTableData;
			//应付总金额
			params.amountPayable = this.Model.totlePrice;
			//订单金额
			params.orderAmount = this.Model.totlePrice;
			//支付金额
			params.payAmount = this.Model.totlePrice;

			if (this.Model.params.shippingMethod == '0') {
				//收货信息
				params.saleReceivingList = [this.Model.checkedAddress];
			} else {
				//自提信息
				params.saleReceivingList = [this.Model.userSelfLift];
			}
			this.Model.newLoading = true;
			this.getNewOrder(this, params, pathName)
		},
		//跳转到添加支付信息 赠品信息
		toAddPayGift(pathName) {
			this.onConfirmSubmit(pathName);
		},
		//点击取消订单
		cancelOrder() {
			this.$router.push({
				path: 'spotOrder',
				query: {

				}
			});
		},
		//
		showNotSureBarCodeP1() {

		},
		showNotSureBarCodeP2() {

		},
		toSearchNotSureBarCode() {

		},
		//
		selectedHighlight(data) {
			// 如果选中则添加高亮样式
			if (this.Model.TableSelectData.indexOf(data.row) > -1) {
				return {
					"background-color": "#FEF6EE"
				};
				return {}
			}
		},
		//点击行 选中单选框
		handleRowClick(row){
			this.Model.dialogTableChecked = row;
		},
		tips(that, type, message) {
			let duration;
			type == 'success' ? duration = 3000 : duration = 10000;
			that.$message({
				message: message,
				type: type,
				duration: duration
			});
		},
		handleSelectionChange(val) {
			this.Model.TableSelectData = val;
		},
		handleCurrentChange(val) {
			this.Model.pager.params.pageIndex = val;
		},
		handleSizeChange(val) {
			this.Model.pager.params.pageSize = val;
		},
		cardClick(color) {
			this.Model.cardSelected = color;
		},
		showChild(val) {
			this.Model.searchFromData = val;
		},
		toSearch(val) {
			var params = this.Model.searchFromData
			this.getCommodity(this, params)
		},
		toClear(val) {
			this.Model.searchFromData = this.Model.defaultSearchFromData;
		},
		toExport(val) {
			console.log(val);
		},
		//切换省市区
		handleItemChange(val) {
			console.log(val)
			if (val.length == 1) {
				var provinceCode = val[0];
				this.getAllCity(this, provinceCode);
			} else if (val.length == 2) {
				var provinceCode = val[0];
				var cityCode = val[1];
				this.getAllCounty(this, provinceCode, cityCode)
			} else {

			}
		},
		//联机选择器 选择结束触发
		changecascards(val) {
			var labelStr = '';
			var cascaderArr = this.getCascaderObj(val, this.Model.options);
			for (let i = 0; i < cascaderArr.length; i++) {
				labelStr += cascaderArr[i].label;
			}
			// this.Model.checkedAddress.location = labelStr;
			this.Model.checkedAddress.countryCode = 'CN';
			this.Model.checkedAddress.countryName = '中国';
			this.Model.checkedAddress.provinceCode = cascaderArr[0].code;
			this.Model.checkedAddress.provinceName = cascaderArr[0].label;
			this.Model.checkedAddress.cityCode = cascaderArr[1].code;
			this.Model.checkedAddress.cityName = cascaderArr[1].label;
			this.Model.checkedAddress.areaCode = cascaderArr[2].code;
			this.Model.checkedAddress.areaName = cascaderArr[2].label;
			console.log(this.Model.checkedAddress)
		},
		//遍历 得到label及value
		getCascaderObj(val, opt) {
			return val.map(function(value, index, array) {
				for (var item of opt) {
					if (item.code == value) {
						opt = item.children;
						return item;
					}
				}
				return null;
			});
		},
		//合计
		getSummaries(param) {
			var that = this;
			const {
				columns,
				data
			} = param;
			const sums = [];
			columns.forEach((column, index) => {
				if (index === 0) {
					sums[index] = '总价';
					return;
				} else if (index === 5 || index === 6 || index === 7 || index === 8) {
					const values = data.map(item => Number(item[column.property]));
					sums[index] = values.reduce((prev, curr) => {
						const value = Number(curr);
						if (!isNaN(value)) {
							return prev + curr;
						} else {
							return prev;
						}
					}, 0);
					if (index === 6) {
						that.Model.totlePrice = sums[index];
					} else {

					}

				} else {
					sums[index] = '/';
				}
			});

			return sums;
		}
	}
}
export default Controller;
